#include "remoteselector.h"




RemoteSelector::RemoteSelector(QBluetoothAddress &localAdapter, QWidget *parent)
{
    m_discoveryAgent = new QBluetoothServiceDiscoveryAgent(localAdapter);

       // 连接信号和槽
    connect(m_discoveryAgent, SIGNAL(serviceDiscovered(QBluetoothServiceInfo)),
               this, SLOT(serviceDiscovered(QBluetoothServiceInfo)));
    connect(m_discoveryAgent, SIGNAL(finished()), this, SLOT(discoveryFinished()));
    connect(m_discoveryAgent, SIGNAL(canceled()), this, SLOT(discoveryFinished()));
}

RemoteSelector::~RemoteSelector()
{
    delete m_discoveryAgent;
}

void RemoteSelector::startDiscovery(const QBluetoothUuid &uuid)
{
    Q_UNUSED(uuid);
    qDebug() << "startDiscovery";

    if (m_discoveryAgent->isActive()) {
        qDebug() << "stop the searching first";
        m_discoveryAgent->stop();
    }

    // 注意：这里注释掉了UUID过滤，否则可能搜索不到手机
    // m_discoveryAgent->setUuidFilter(uuid);

    // 开始全发现模式
    m_discoveryAgent->start(QBluetoothServiceDiscoveryAgent::FullDiscovery);
}

void RemoteSelector::stopDiscovery()
{
    qDebug() << "stopDiscovery";
    if (m_discoveryAgent) {
        m_discoveryAgent->stop();
    }
}

QBluetoothServiceInfo RemoteSelector::service() const
{
    return m_serviceInfo;
}

void RemoteSelector::serviceDiscovered(const QBluetoothServiceInfo &serviceInfo)
{
    // 调试信息（已注释掉）
#if 0
    qDebug() << "Discovered service on"
             << serviceInfo.device().name() << serviceInfo.device().address().toString();
    qDebug() << "\tService name:" << serviceInfo.serviceName();
    qDebug() << "\tDescription:"
             << serviceInfo.attribute(QBluetoothServiceInfo::ServiceDescription).toString();
    qDebug() << "\tProvider:"
             << serviceInfo.attribute(QBluetoothServiceInfo::ServiceProvider).toString();
    qDebug() << "\tL2CAP protocol service multiplexer:"
             << serviceInfo.protocolServiceMultiplexer();
    qDebug() << "\tRFCOMM server channel:" << serviceInfo.serverChannel();
#endif

    // 检查是否已经发现了该设备
    QMapIterator<QString, QBluetoothServiceInfo> i(m_discoveredServices);
    while (i.hasNext()) {
        i.next();
        if (serviceInfo.device().address() == i.value().device().address()) {
            return; // 如果已经存在，则跳过
        }
    }

    // 获取远程设备名称
    QString remoteName;
    if (serviceInfo.device().name().isEmpty()) {
        remoteName = serviceInfo.device().address().toString();
    } else {
        remoteName = serviceInfo.device().name();
    }

    qDebug() << "adding to the list....";
    qDebug() << "remoteName: " << remoteName;

    // 创建列表项并发出信号
    QListWidgetItem *item = new QListWidgetItem(QString::fromLatin1("%1 %2")
                                                .arg(remoteName, serviceInfo.serviceName()));

    m_discoveredServices.insert(remoteName, serviceInfo);
    emit newServiceFound(item);
}

void RemoteSelector::discoveryFinished()
{
    qDebug() << "discoveryFinished";
    emit finished();
}
